package com.speed_run.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.speed_run.dto.Article;
import com.speed_run.dto.Strategy;
import com.speed_run.global.GlobalMethod;
import com.speed_run.mapper.AdminMapper;
import com.speed_run.mapper.CircleMapper;
import com.speed_run.model.Circle;
import com.speed_run.service.IAdminService;
import com.speed_run.utils.ImageUtils;
import com.speed_run.utils.ResponseEntity;

import lombok.Data;

@Service
public class AdminCircleServiceImpl implements IAdminService {
	
	@Autowired
	private CircleMapper cMapper;
	
	@Autowired
	private AdminMapper aMapper;
	
	
	@Value("${config.host}")
	private String host;
	
	@Override
	@Transactional
	public ResponseEntity updateCirlce(MultipartFile pic, Integer id, String name, String introduce) throws Exception {
		
		Circle c = cMapper.getCircleById(id);
		String relativePath = "";
		if(c == null) {
			c = new Circle();
			c.setName(name);
			c.setIntroduce(introduce);
			c.setCreateDate(new Date());
			c.setNumber(0);
			c.setStatus(0);
			if(pic != null) {
		        String picName = pic.getOriginalFilename().toLowerCase();
		        try {
		        	relativePath = GlobalMethod.getRelativePath(picName.substring(picName.lastIndexOf(".")).split("\\.")[1],"pic");
		            String filePath = GlobalMethod.getFilepath(relativePath);
		            File frameFile = new File(filePath);
		            frameFile.createNewFile();
		            pic.transferTo(frameFile);
		            c.setPic(relativePath);
		        }catch (Exception e){
		        	e.printStackTrace();
		        	throw e;
		        }
			}
			cMapper.insertCircle(c);
		}else {
			c.setName(name);
			c.setIntroduce(introduce);
			if(pic != null) {
		        String picName = pic.getOriginalFilename().toLowerCase();
		        try {
		            relativePath = GlobalMethod.getRelativePath(picName.substring(picName.lastIndexOf(".")).split("\\.")[1],"pic");
		            String filePath = GlobalMethod.getFilepath(relativePath);
		            File frameFile = new File(filePath);
		            frameFile.createNewFile();
		            pic.transferTo(frameFile);
		            c.setPic(relativePath);
		        }catch (Exception e){
		        	e.printStackTrace();
		        	throw e;
		        }
		        c.setPic(relativePath);
			}
			cMapper.updateCircle(c);
		}
		 return ResponseEntity.ok("success");
	}
 
	@Override
	public ResponseEntity getCircleTable(Integer pageNum) {
		PageHelper.startPage(pageNum, 5); 
		List<Map<String, Object>> result = cMapper.getCircleTableData();
		for (Map<String, Object> map : result) {
			if(map.get("avatar") != null){
				map.put("avatar", this.host+map.get("avatar"));
			}
			if(map.get("number") == null) {
				map.put("number", 0);
			}
			if(map.get("dayPost") == null) {
				map.put("dayPost", 0);
			}
		}
		return ResponseEntity.ok("success",result);
	}

	@Override
	public ResponseEntity getFocusImgs() {
		List<Map<String, Object>> data = aMapper.getFocusImgs();
		for (Map<String, Object> map : data) {
			map.put("path", host+map.get("path"));
		}
		return ResponseEntity.ok("success", data);
	}

	@Override
	public ResponseEntity updateImg(Integer id, MultipartFile img) {
		Map<String ,Object> data=null;
		if(img == null) {
			return ResponseEntity.ok("success",img);
		}
		data = aMapper.getImgById(id);
		data.put("path", getImgPath(img,120,50));
		data.put("updateDate", new Date());
		data.put("id", id);
		aMapper.updateImg(data);
		data.put("path", host+data.get("path"));
		return ResponseEntity.ok("success",data);
	}

	@Override
	public ResponseEntity delImg(Integer id) {
		aMapper.delImg(id);
		return ResponseEntity.ok("success");
	}

	@Override
	public ResponseEntity insertImg(MultipartFile imgFile) {
		Date date = new Date();
		FocusImg img = new FocusImg();
		img.setPath(getImgPath(imgFile,120,50));
		img.setUpdateDate(date);
		img.setCreateDate(date);
		aMapper.insertImg(img);
		return ResponseEntity.ok("success",img);
	}
	
	private String getImgPath(MultipartFile imgFile,Integer width, Integer height){
		 String fileName = imgFile.getOriginalFilename().toLowerCase();
		 String relativePath = GlobalMethod.getRelativePath(fileName.substring(fileName.lastIndexOf(".")).split("\\.")[1],"pic");
         String filepath = GlobalMethod.getFilepath(relativePath);
         String zipFilePath = filepath.substring(0,filepath.lastIndexOf("."));
         
    	 File avatorFile = new File(filepath);
		
		 try {
			 avatorFile.createNewFile();
			imgFile.transferTo(avatorFile);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
         zipFilePath = zipFilePath + "pre.jpg";
         ImageUtils.reduceImg(filepath,zipFilePath,width,height,null);
         return relativePath.substring(0,relativePath.lastIndexOf("."))+"pre.jpg";
	}
	
	
	
	@Data
	class FocusImg {
		private Integer id;
		private String path;
		private Date createDate;
		private Date updateDate;
	}

	@Override
	public ResponseEntity updateStrategy(String name, Integer id, MultipartFile img) {
		Date date = new Date();
		Strategy s  = null;
		if(id == null) {
		   s = new Strategy();
		   s.setCreateDate(date);
		   s.setIsDeleted(0);
		   s.setName(name);
		   s.setImg(getImgPath(img,60,60));
		   s.setUpdateDate(date);
		}else {
		   s = aMapper.findStrategyById(id);
		   if(s != null) {
		       if(img != null) {
		    	   s.setImg(getImgPath(img,60,60));
		       }
		       s.setUpdateDate(date);
	    	   s.setName(name);
		       aMapper.updateStrategy(s);
		       return ResponseEntity.ok("操作成功",s);
		   }
		}
		return ResponseEntity.ok("操作成功",s);
	}

	@Override
	public ResponseEntity getALLStrategy() {
		List<Map<String, Object>> result = aMapper.findStratey();
		for (Map<String, Object> map : result) {
			map.put("img",host+map.get("img"));
		}
		return ResponseEntity.ok("success",result);
	}

	@Override
	public ResponseEntity getArticleById(Integer id) {
		List<Map<String, Object>> result = aMapper.findArticleByPId(id);
		for (Map<String, Object> map : result) {
			map.put("img",host+map.get("img"));
		}
		return ResponseEntity.ok("success",result);
	}

	@Override
	public ResponseEntity updateArticle(String name, Integer id, MultipartFile img) {
		Date date = new Date();
		Article s  = null;
		if(id == null) {
		   s = new Article();
		   s.setCreateDate(date);
		   s.setIsDeleted(0);
		   s.setName(name);
		   s.setImg(getImgPath(img,60,60));
		   s.setUpdateDate(date);
		}else {
		   s = aMapper.findArticleById(id);
		   if(s != null) {
		       if(img != null) {
		    	   s.setImg(getImgPath(img,60,60));
		       }
		       s.setUpdateDate(date);
	    	   s.setName(name);
		       aMapper.updateArticle(s);
		       return ResponseEntity.ok("操作成功",s);
		   }
		}
		return ResponseEntity.ok("操作成功",s);
	}
}
